#include"comment.h"
#include<string.h>  //strcmp函数
#include<stdlib.h>  //exit函数
#include<sys/wait.h>    //waitpid函数
int main()
{
    umask(0);//清空权限掩码
    if(mkfifo(MY_FIFO,0666)<0)  //创建管道
    {
        perror("mkfifo:");
        return 1;
    }
    int fd = open(MY_FIFO,O_RDONLY);//以读方式打开
    if(fd<0)
    {
        perror("open");
        return 2;
    }

    //处理业务逻辑,进行相应的读写
    while(1)
    {
        
        char buffer[64] = {0};
        ssize_t s =  read(fd,buffer,sizeof(buffer)-1);//少读一个字节,防止读满了之后在末尾置\0越界
        if(s > 0)
        {
            //读取成功
            buffer[s] = 0;//字符串末尾置\0
            if(strcmp(buffer,"show-ls-l") == 0)
            {
                if(fork() == 0)//创建子进程帮我们干活
                {
                    execl("/usr/bin/ls","ls","-l",NULL);//进程替换
                    exit(1);//进程替换成功之后是不会走到这里的
                }
                waitpid(-1,NULL,0);
            }
            else if(strcmp(buffer,"show-train") == 0 )   //小火车
            {
                if(fork() == 0)
                {
                    execl("/usr/bin/sl","sl",NULL);
                    exit(1);
                }
                waitpid(-1,NULL,0);
            }
            else
            {
                printf("client send:%s\n",buffer);
            }
        }
        else if(s == 0)
        {
            //对端关闭了
            printf("client close\n");
            break;
        }
        else
        {
            //读取错误
            perror("read:");
            break;
        }
    }
    close(fd);
    return 0;
}
